<?php

    define('ACC',true);
require_once('./include/init.php');

    $get = $_GET;

    //设置一个动作参数  判断用户想干什么，比如是下订单/写地址/提交/清空购物车等
    $act = isset($get['act'])?$get['act']:'buy';

    $goods = new goodModel;
    $cart = CartTool::getCart();

    if($act == 'buy') {  //把商品添加到购物车
        $goods_id = isset($get['goods_id']) ? $get['goods_id'] + 0 : 0;
        $num = isset($get['num']) ? isset($get['num']) + 0 : 1;
        if ($goods_id) { //$goods_id 为真，是想吧商品放到购物车里
            $goodRow = $goods->getOneGoods($goods_id);  //从数据库获取加购商品信息
            if (!empty($goodRow)) {
                //判断商品状态是否是上架状态是否在回收站  *** 这个直接放后台处理器 ，只取正常上架，不在回收站的产品
                //判断商品库存是否够
                $catAll = $cart->all();

                if(isset($catAll[$goods_id])){
                    if(!$goodRow['goods_number'] || $goodRow['goods_number'] < $catAll[$goods_id]['num']) {
                        $messge = '商品库存不足!';
                        sendMsg($messge);
//                        include('./view/front/messge.html');
//                        exit;
                    }
                }else {
                    if(!$goodRow['goods_number']) {
                        $messge = '商品库存不足!';
                        sendMsg($messge);
//                        include('./view/front/messge.html');
//                        exit;
                    }
                }
                $cart->addItem($goodRow['goods_id'], $goodRow['goods_name'], $goodRow['shop_price'], $num); //将该条加购信息放到session
            }
        }
        //获取所有加购商品信息
        $catAll = $cart->all();
        $catDetail = $goods->getCatDetail($catAll);

        $total = $cart->getPrice();   //总价
        $market_total  = 0;   //市场价
        foreach($catDetail as $v){
            $market_total += $v['market_price'] * $catAll[$v['goods_id']]['num'];
        }
        $discount = $market_total - $total;
        $rate = '';
        if($market_total){
            $rate = round(100 * ($market_total-$total)/$total,2);
        }

        require_once('./view/front/jiesuan.html');

    }elseif ($act == 'clear'){
        $cart->clear();
        $messge = '清空购物车成功';
        require_once('./view/front/messge.html');

    }elseif($act == 'tijiao' ){

        //购物车点击提交订单页面
        //获取所有加购商品信息
        $catAll = $cart->all();
        $catDetail = $goods->getCatDetail($catAll);

        $total = $cart->getPrice();   //总价
        $market_total  = 0;   //市场价
        foreach($catDetail as $v){
            $market_total += $v['market_price'] * $catAll[$v['goods_id']]['num'];
        }
        $discount = $market_total - $total;
        if($market_total){
            $rate = round(100 * $total/$market_total,2);
        }

        require_once('./view/front/tijiao.html');
    }elseif($act == 'done'){
        /**
         * 提交订单后
         * 1，将订单信息写入数据库
         * 2，将订单字表信息写入数据库
         * 3，更改商品库存信息
         * 4，清空购物车
         */

        $data = $_POST;
        $orderInfo = new orderInfoModel;
        //自动过滤
        $data = $orderInfo->shiftData($data);

        //自动验证
        if(!$orderInfo->_validate($data)){
            $messge = implode(',',$orderInfo->getErr());
            require_once('./view/front/messge.html');
            exit();
        }

        $orderGoods = new orderGoodsModel;
        $orderSn = $orderInfo->autoSn();
        $sumPrice = $cart->getPrice();

        $data['order_sn'] = $orderSn;
        $data['add_time'] = time();
        $data['user_id'] = isset($_SESSION['user_id'])?$_SESSION['user_id']:0;
        $data['user_name'] = isset($_SESSION['username'])?$_SESSION['username']:0;
        $data['order_amount'] = $sumPrice;

        //将订单数据添加到数据库
        if(!$orderInfo->add($data)){
            $messge = '订单提交失败';
            require_once('./view/front/messge.html');
            exit();
        }

        $orderId = $orderGoods->insertId();
        $catAll = $cart->all();
        $local = 0;  //记录订单详情表的商品个数
        foreach($catAll as $k=>$v){
            //将购物车的每个商品数据一条一条的添加到订单详情表
            $item = [];
            $item['order_id'] = $orderId;
            $item['order_sn'] = $orderSn;
            $item['goods_id'] = $k;
            $item['goods_name'] = $v['name'];
            $item['goods_number'] = $v['num'];
            $item['shop_price'] = $v['price'];
            $item['subtotal'] = $sumPrice;


            if(!$orderGoods->addGoods($item)){
                $messge = '订单提交失败';
                require_once('./view/front/messge.html');
                exit();
            }


            $local += 1;
        }

        //比较购物车总商品数是否等于 加入详情表的商品总数
        if(count($catAll) !== $local){
            /**
             * 两者不相等说明数据有问题，购物车的数据没有全部添加到表里
             * 这时我们要回滚之前对数据的操作
            */
            $orderInfo->invoke($orderId);
            $messge = '订单提交失败';
            require_once('./view/front/messge.html');
            exit();
        }

        //清空购物车
        $cart->clear();

        //

         $messge = '订单成功';

        require_once('./view/front/order.html');

    }


     function sendMsg($msg){
         print_r('in ... msg ..');
         $messge = $msg;
         require_once('./view/front/messge.html');
         exit;
     }


